<?php
/**
 * XmuSlh, web platform of Student Association Federation of Xiamen University
 * 
 * Rewritting one or some pages of StatusNet. 
 * To get the original version, please visit <http://status.net/>.
 * 
 * StatusNet, the distributed open-source microblogging tool
 * 
 * LICENCE: This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * The File class for table 'file'.
 * 
 * @author		ytukie <ytukie@gmail.com>
 * @version		0.2
 * 
 * 0.2)  Adjusts the structure of the table.
 * 		 Removes the fileurl and filepath, adds the originalname.
 */

// XmuSlh only.
if ( !defined('XMUSLH')) { exit(1); }

require_once INSTALLDIR . '/lib/slh_util.php';
require_once INSTALLDIR . '/classes/Memcached_DataObject.php';

require_once INSTALLDIR . '/lib/slh_clientexception.php';

// Definitions.
// Column of status reserves.

class File extends Memcached_DataObject
{
	public $__table = 'file';			// table name
	public $id;							// int(11)  primary_key not_null
	public $status;						// tinyint(4)
	public $filename;					// varchar(255)  unique
	public $originalname;				// varchar(255)
	public $mimetype;					// varchar(32)
	public $size;						// int(11)
	
	function __construct($id = null,
						 $status = null,
						 $filename = null,
						 $originalname = null,
						 $mimetype = null,
						 $size = null)
	{
		$this->id = $id;
		$this->status = $status;
		$this->filename = $filename;
		$this->originalname = $originalname;
		
		// TODO: Some mime type and poffix limitations.
		$this->mimetype = $mimetype;
		
		$this->size = $size;
	}
	
	// Static get
	function staticGet($key, $value = null)
	{
		return Memcached_DataObject::staticGet('File', $key, $value); 
	}
	
	/**
	 * Get the file path.
	 */
	function filepath()
	{
		return File::path($this->filename);
	}
	
	/**
	 * Get the file url.
	 */
	function fileurl()
	{
		return File::url($this->filename);
	}
	
	/**
	 * Delete a file in the database and filesystem.
	 */
	function delete()
	{
		@unlink($this->filepath());
		
		parent::delete();
	}
	
	/**
	 * Where should be the file go?
	 */
	static function filename($filename, $mimetype)
	{
		// Get the ext-poffix by mimetype detection.
		require_once INSTALLDIR . '/extlib/PEAR.php';
		require_once INSTALLDIR . '/extlib/MIME/Type/Extension.php';
		
		// We have to temporarily disable auto handling of PEAR errors...
		PEAR::staticPushErrorhandling(PEAR_ERROR_RETURN);
		
		$mte = new MIME_Type_Extension();
		$ext = $mte->getExtension($mimetype);
		if (PEAR::isError($ext)) {
			$ext = strtolower(preg_replace('/\W/', '', $mimetype));
		}
		
		// Restore error handling.
		PEAR::staticPopErrorHandling();
		
		// Get the ext-poffix by the filename .xxx
		$dotpos = mb_strrpos($filename, '.');
		if ($dotpos) {
			$ext2 = mb_substr($filename, $dotpos + 1);
			
			// For mimetype = 'application/octet-stream', check if is supported file.
			if ($ext2 != $ext) {
				$supportedpoffix = slh_config('file', 'supportedpoffix');
				if (in_array($ext2, $supportedpoffix)) {
					$ext = $ext2;
				} else {
					$ext = 'rename';
				}
			}
		}
		
		return slh_timestamp() . uniqid() . '.' . $ext;
	}
	
	/**
	 * Validation for as-saved base filenames
	 */
	static function validFilename($filename)
	{
		return preg_match('/^[A-Za-z0-9._-]+$/', $filename);
	}
	
	/**
	 * Get the storage path.
	 */
	static function path($filename)
	{
		if ( !self::validFilename($filename)) {
			throw new ClientException('Invalid filename');
			return;
		}
		
		$dir = slh_config('file', 'dir');
		
		if ($dir[strlen($dir) - 1] != '/') {
			$dir .= '/';
		}
		
		return $dir . $filename;
	}
	
	/**
	 * Get the represented url.
	 */
	static function url($filename)
	{
		if ( !self::validFilename($filename)) {
			throw new ClientException('Invalid filename');
			return;
		}
		
		$server = slh_config('file', 'server');
		$path = slh_config('file', 'path');
		
		if (empty($server)) {
			$server = slh_config('site', 'server');
		}
		
		if ($path[strlen($path) - 1] != '/') {
			$path .= '/';
		}
		if ($path[0] != '/') {
			$path = '/' . $path;
		}
		
		return 'http://' . $server . $path . $filename;
	}
}
?>